﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        IPAddress ip;//创建ip
        TcpListener listener;//创建TCP监听对象
        TcpClient tcpClient;//得到客户端的TCP
        FileStream fs;
        string UploadPath;//上传路径

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();

        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            IPAddress ipAddr = Dns.Resolve(Dns.GetHostName()).AddressList[0];//获得当前IP地址
            string ip = ipAddr.ToString();
            //ip = IPAddress.Parse(textBoxIP.Text);//创建ip
            listener = new TcpListener(IPAddress.Any, Convert.ToInt32(textBoxPort.Text)/*转为int*/);//创建TCP监听对象
            textBoxIP.Text = ip;
            listener.Start();//开始监听
            textBoxInfo.Text = "服务器启动" + "\r\n" + textBoxInfo.Text;
            tcpClient = listener.AcceptTcpClient();//监听，中断，等待
            textBoxInfo.Text = "连接成功" + "\r\n" + textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();




            while (true)
            {
                byte[] byteArray = new byte[1024];
                int length = stream.Read(byteArray, 0, byteArray.Length);//将流里的字节数组放到bayArray里边
                string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);

                //MessageBox.Show(receiveMessage);

                string FileLength = "", FileName = "", UserFolder = "";
                if (receiveMessage.Substring(0, 1) == "|")//新建用户文件夹
                {
                    UserFolder = receiveMessage.Substring(1, receiveMessage.Length - 1);
                    string activeDir = @"C:\\";
                    string newPath = Path.Combine(activeDir, UserFolder);
                    Directory.CreateDirectory(newPath);
                    continue;
                }
                else if (receiveMessage.Substring(0, 1) == ">")//下载文件
                {
                    receiveMessage = receiveMessage.Substring(1, receiveMessage.Length - 1);
                    UploadPath = receiveMessage;

                    Upload();

                    continue;
                }
                else if (receiveMessage.Substring(0, 1) == "*")//删除文件
                {
                    File.Delete(string.Format(@"C:\\{0}", receiveMessage.Substring(1, receiveMessage.Length - 1)));
                    continue;
                }
                else if (receiveMessage == "END")
                {
                    Process pr = new Process();
                    pr.StartInfo.FileName = "server.exe";
                    pr.Start();
                    this.Close();
                    continue;
                } else if (receiveMessage.Substring(0, 1) == "?")
                {
                    receiveMessage = receiveMessage.Substring(1, receiveMessage.Length - 1);
                    string[] a = receiveMessage.Split('?');
                    string oldname = "",newname="";
                    oldname = a[1];
                    newname = a[0];
                    FileInfo FI = new FileInfo("C:\\"+ oldname);

                    FI.MoveTo(Path.Combine("C:\\" + newname));




                    continue;

                }
                else if (Find(receiveMessage) == true)
                {//发送文件信息
                    string[] a = new string[3];
                    a = receiveMessage.Split('<');
                    FileLength = a[0];//文件大小
                    FileName = a[1];//文件名
                    UserFolder = a[2];//存放的用户文件夹
                    //MessageBox.Show("上传文件" + receiveMessage);

                    byte[] section = new byte[256];//接收文件
                    int index = 0;
                    byte[] bits = new byte[int.Parse(FileLength)];
                    for (int num = 0; num <= int.Parse(FileLength) / 256 + 1; num++)
                    {
                        stream.Read(section, 0, section.Length);
                        for (int j = 0; index < int.Parse(FileLength); j++, index++)
                        {
                            if (j == 256)
                            {
                                j = 0;
                                break;
                            }
                            bits[index] = section[j];
                        }
                    }
                    MemoryStream ms = new MemoryStream(bits);
                    File.WriteAllBytes(string.Format("C:\\{0}\\{1}", UserFolder, FileName), bits);
                    Array.Clear(bits, 0, bits.Length);
                    receiveMessage = "";



                }

                

            }






        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private static bool Find(string str)
        {
            bool a = false;

            for (int i = 0; i < str.Length;i++ )
            {
                if(str.Substring(i,1)=="<")
                {
                    a = true;
                }
            }

            return a;
        
        }


        private void Upload()
        {
            //this.openFileDialog1.ShowDialog();
            fs = new FileStream(string.Format("C:\\{0}",UploadPath), FileMode.Open, FileAccess.Read);
            byte[] infbytes = new byte[fs.Length];

            string FileName = "";
            for (int index = this.openFileDialog1.FileName.Length - 1; index >= 0; index--)
            {
                if (this.openFileDialog1.FileName.Substring(index, 1) == "\\")
                {
                    FileName = this.openFileDialog1.FileName.Substring(index + 1);
                    break;
                }
            }

            NetworkStream stream = tcpClient.GetStream();
            byte[] bytrArray = Encoding.Unicode.GetBytes(fs.Length + "<" + FileName);//将要发送的数据转化成为一个字节数组
            Thread.Sleep(10);

            stream.Write(bytrArray, 0, bytrArray.Length);//发送文件长度

            //发送文件
            byte[] section = new byte[256];
            int i = 0;
            for (int num = 0; num <= fs.Length / 256 + 1; num++)
            {
                //label3.Text = num + "";
                for (int j = 0; i < infbytes.Length; j++, i++)
                {
                    if (j == 256)
                    {
                        j = 0;
                        break;
                    }
                    section[j] = infbytes[i];
                }
                fs.Read(section, 0, section.Length);
                stream.Write(section, 0, section.Length);//发送字节流*/
            }

            //pictureBox1.Image = Image.FromStream(fs);
            textBoxInfo.Text = "发送文件" + "\r\n" + textBoxInfo.Text;
            //NetworkStream stream1 = TcpClient.GetStream();


        }


        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = textBoxInput.Text;
            textBoxInfo.Text = "发送" + message + "-" + "\r\n" + textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();
            byte[] bytrArray = Encoding.Unicode.GetBytes(message);//将要发送的数据转化成为一个字节数组
            stream.Write(bytrArray, 0, bytrArray.Length);//发送字节流
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            fs = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
            byte[] infbytes = new byte[fs.Length];

            string FileName = "";
            for (int index = this.openFileDialog1.FileName.Length - 1; index >= 0; index--)
            {
                if (this.openFileDialog1.FileName.Substring(index, 1) == "\\")
                {
                    FileName = this.openFileDialog1.FileName.Substring(index + 1);
                    break;
                }
            }

            NetworkStream stream = tcpClient.GetStream();
            byte[] bytrArray = Encoding.Unicode.GetBytes(fs.Length + "<" + FileName);//将要发送的数据转化成为一个字节数组
            stream.Write(bytrArray, 0, bytrArray.Length);//发送文件长度

            //发送文件
            byte[] section = new byte[256];
            int i = 0;
            for (int num = 0; num <= fs.Length / 256 + 1; num++)
            {
                //label3.Text = num + "";
                for (int j = 0; i < infbytes.Length; j++, i++)
                {
                    if (j == 256)
                    {
                        j = 0;
                        break;
                    }
                    section[j] = infbytes[i];
                }
                fs.Read(section, 0, section.Length);
                stream.Write(section, 0, section.Length);//发送字节流*/
            }
            
            //pictureBox1.Image = Image.FromStream(fs);
            textBoxInfo.Text = "发送文件" + "\r\n" + textBoxInfo.Text;
            //NetworkStream stream1 = TcpClient.GetStream();
            

        }
    }
}
